package com.demo.base.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.info.MultimediaInfo;

import java.io.File;
import java.util.UUID;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 获取上传音视频文件的时长
 * @date 2023/4/1 9:48 PM
 */
@Slf4j
public class SourceDurationUtil {
    /**
     * 获取音视频时长
     *
     * @param multipartFile
     * @return
     */
    public static Long getSourceDuration(MultipartFile multipartFile) {

        File source = multipartFileToFile(multipartFile);
        if (source == null) {
            log.error("MultipartFile 转 File 失败，文件为空");

            return 0L;
        }

        try {
            // 解析文件
            MultimediaObject object = new MultimediaObject(source);
            MultimediaInfo multimediaInfo = object.getInfo();
            long duration = multimediaInfo.getDuration();

            log.debug("文件：{}，时长ms：{}", source.getAbsolutePath(), duration);
            return duration / 1000;

        } catch (Exception e) {
            log.error("文件时长获取失败，异常：{}", e.getMessage());
        } finally {
            // 删除文件
            if (source.exists()) {
                if (!source.delete()) {
                    log.error("删除文件File失败");
                } else {
                    log.info("文件：{} ，已删除", source.getAbsolutePath());
                }
            }
        }

        return 0L;
    }

    /**
     * 获取音视频时长
     *
     * @param source
     * @return
     */
    public static Long getSourceDuration(File source) {

        try {
            // 解析文件
            MultimediaObject object = new MultimediaObject(source);
            MultimediaInfo multimediaInfo = object.getInfo();
            long duration = multimediaInfo.getDuration();

            log.debug("文件：{}，时长ms：{}", source.getAbsolutePath(), duration);
            return duration / 1000;

        } catch (Exception e) {
            log.error("文件时长获取失败，异常：{}", e.getMessage());
        }

        return 0L;
    }

    /**
     * MultipartFile 转 File
     *
     * @param multiFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multiFile) {

        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            return null;
        }

        // 生成新文件名
        String newFileName = UUID.randomUUID().toString().replace("-", "");

        try {
            File file = File.createTempFile(newFileName, suffix, new File("/tmp"));
            multiFile.transferTo(file);

            return file;
        } catch (Exception e) {
            log.error("MultipartFile 转 File 失败，异常：{}", e.getMessage());
        }

        return null;
    }
}
